<!DOCTYPE html>
<html>
<head>
    <!-- 
	<meta name="mobile-web-app-capable" content="yes">
	<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"/>
	<meta charset="UTF-8">
    <link rel="stylesheet" href="../../script/semantic/semantic.min.css">
    <script src="../../script/jquery.min.js"></script>
	<script src="../../script/semantic/semantic.min.js"></script>
    -->
    <style>
        .hidden{
            display:none;
        }

        .disabled{
            opacity: 0.5;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="ui form">
        <!-- 
        <div class="field">
            <div class="ui toggle checkbox">
                <input id="enabled" type="checkbox" name="enable" onchange="toggleFTPServer(this.checked);">
                <label>Enable FTP Server</label>
            </div>
        </div>
        -->
        <div class="field">
            <div class="ui toggle checkbox">
                <input id="useUPNP" type="checkbox" name="upnp" onchange="toggleUPNP(this.checked);">
                <label>Enable UPnP on FTP Server Port</label>
                <small>Aka Auto Port Forwarding. Disable this option if you are connecting within Local Area Network</small>
            </div>
        </div>
        <div class="field">
            <label>Listening Port</label>
            <div class="ui labeled input">
                <input id="listeningPort" type="number" placeholder="21" min="21" onchange="updateFTPPort(this.value)">
            </div>
        </div>
        
        <div class="field">
            <label>Enable FTP access to the following user groups: </label>
            <select id="grouplist" name="groups" multiple="" class="ui fluid dropdown">
                <option value="">User Groups</option>
                
            </select>
            <small><a href="../vendor/public/ftpForAdmin.html" target="_blank">Why enable FTP on administrator account is not a good idea?</a></small>
        </div>
        <div class="field">
            <button onclick="updateGroupAccess();" class="ui secondary right floated button">Update Access Policy</button>
        </div>
        <br><br>
        <div id="ok" class="ui secondary inverted green segment" style="display:none;">
            <i class="checkmark icon"></i> Setting Applied
        </div>
        <div id="error" class="ui secondary inverted red segment" style="display:none;">
            <i class="remove icon"></i> <span class="msg">Something went wrong</span>
        </div>
        <div class="ui divider"></div>
        <h4>Advance Options</h4>
        <br>
        <div class="field">
            <div class="ui toggle checkbox">
                <input id="passiveMode" type="checkbox" name="passivemode" onchange="handlePassiveModeChange(this.checked);">
                <label>Force Passive Mode</label>
                <small>Required under UPnP mode. Optional in default mode with manual port forwarding in gateway router</small>
            </div>
        </div>
        <div class="field">
            <label>Passive Mode Public IP Address</label>
            <div class="ui labeled input">
                <input id="publicip" type="text">
            </div>
            <small>The public IP address of your NAT router. Currently only support IP address.</small>
        </div>
        <div class="field">
            <button onclick="updatePublicIPSetting();" class="ui secondary right floated button">Update Public IP Setting</button>
        </div>
       
    </div>
    <br><br>
    <script>
        var serverAllowUPNP = false;
        var isMac = navigator.platform.indexOf('Mac') > -1;
        var isWindows = navigator.platform.indexOf('Win') > -1;

        if (isMac){
            $(".maconly").show();
        }else if (isWindows){
            $(".windowsonly").show();
        }
        $(document).ready(function(){
            //Load usergroups
            $.get("../../system/permission/listgroup", function(data){
                if (data.error !== undefined){
                    console.log(data.error);
                }else{
                    data.forEach(group => {
                        $("#grouplist").append(` <option value="${group}">${group}</option>`);
                    });
                    
                }
                $(".ui.dropdown").dropdown();

                //Init server status
                //Update done by service.html
                initFTPServerStatus();
            });

            
        });

        function initFTPServerStatus(){
            //Load current system status
            $.get("../../system/storage/ftp/status", function(data){
                if (data.error !== undefined){
                    console.log(data.error);
                }else{
                    if (data.Enabled == true){
                        //$("#enabled")[0].checked = true;
                        $("#useUPNP").parent().removeClass("disabled");
                    }else{
                        $("#listeningPort").parent().addClass("disabled");
                        $("#useUPNP").parent().addClass("disabled");
                    }

                    $("#listeningPort").val(data.Port);
                    $(".port").text(data.Port);

                    if (data.AllowUPNP == false){
                        $("#useUPNP").parent().addClass("disabled");
                        serverAllowUPNP = false;
                    }else{
                        $("#useUPNP").parent().removeClass("disabled");
                        serverAllowUPNP = true;
                    }

                    if (data.FTPUpnpEnabled == true){
                        $("#useUPNP")[0].checked = true;

                        //Disable the chnage of force passive mode and public ip address
                        $("#passiveMode")[0].checked = true;
                        $("#passiveMode").parent().addClass("disabled");
                        $("#publicip").val(data.PublicAddr);
                        $("#publicip").parent().addClass("disabled");
                    }else{
                        $("#useUPNP")[0].checked = false;

                       //Restore to non UPnP passive mode setting
                        $("#passiveMode")[0].checked = data.PassiveMode;
                        $("#passiveMode").parent().removeClass("disabled");
                        $("#publicip").val(data.PublicAddr);
                        $("#publicip").parent().removeClass("disabled");
                    }

                    if (data.UserGroups !== undefined){
                        $('#grouplist').dropdown('set selected', data.UserGroups);
                    }

                    if (data.PassiveMode){
                        $("#passiveMode")[0].checked = true;
                    }else{
                        $("#passiveMode")[0].checked = false;
                    }

                    if (data.PublicAddr != ""){
                        $("#publicip").val(data.PublicAddr);
                    }else{
                        $("#publicip").val("");
                    }

                }

                //Update tutorial information
                $(".hostname").text(window.location.hostname);
            });
        }

        function toggleFTPServer(enabled){
            if (enabled == true){
                $.get("../../system/storage/ftp/start", function(data){
                    if (data.error != undefined){
                        showError(data.error);
                    }else{
                        showOK();
                        if (serverAllowUPNP){
                            $("#useUPNP").parent().removeClass("disabled");
                        }
                        
                        $("#listeningPort").parent().removeClass("disabled");
                    }
                });
            }else{
                $.get("../../system/storage/ftp/stop", function(data){
                    if (data.error != undefined){
                        showError(data.error);
                    }else{
                        showOK();
                        $("#useUPNP").parent().addClass("disabled");
                        $("#listeningPort").parent().addClass("disabled");
                    }
                });
            }
        }

        function toggleUPNP(enabled){
            if (enabled){
                $.get("../../system/storage/ftp/upnp?enable=true", function(data){
                    if (data.error != undefined){
                        showError(data.error);
                    }else{
                        setTimeout(function(){
                            handleUpnpStateCheck(true);
                        }, 1000);
                    }
                });
            }else{
                $.get("../../system/storage/ftp/upnp?enable=false", function(data){
                    if (data.error != undefined){
                        showError(data.error);
                    }else{
                        setTimeout(function(){
                            handleUpnpStateCheck(false);
                        }, 1000);
                    }
                });
            }
        }

        function handleUpnpStateCheck(expectedUPnPState){
            console.log("Checking UPNP Enabling State")
            $.get("../../system/storage/ftp/status",function(data){
                if (data.FTPUpnpEnabled == expectedUPnPState){
                    //OK
                    showOK();
                }else{
                    //Show error
                    showError("UPnP Port Forward Request Failed");
                    $("#useUPNP")[0].checked = false;
                }

                initFTPServerStatus();
            });
        }

        function updateGroupAccess(){
            var groups = $("#grouplist").dropdown("get value");
            groups = JSON.stringify(groups)
            $.ajax({
                url: "../../system/storage/ftp/updateGroups",
                method: "POST",
                data: {"groups": groups},
                success: function(data){
                    if (data.error != undefined){
                        showError(data.error);
                    }else{
                        showOK();
                    }
                }
            })
        }

        function updatePublicIPSetting(){
            var newip = $("#publicip").val();
            $.ajax({
                url: "../../system/storage/ftp/passivemode",
                data: {set: "ip", "ip": newip},
                success: function(data){
                    if (data.error != undefined){
                        showError(data.error);
                    }else{
                        showOK();
                    }
                }
            })
        }

        function handlePassiveModeChange(value){
            $.ajax({
                url: "../../system/storage/ftp/passivemode",
                data: {set: "mode", "passive": value},
                success: function(data){
                    if (data.error != undefined){
                        showError(data.error);
                    }else{
                        showOK();
                    }
                    initFTPServerStatus();
                }
            })
        }


        function updateFTPPort(portNumber){
            if (portNumber < 21){
                showError("Port number must be > 21")
                return
            }
            $.ajax({
                url: "../../system/storage/ftp/setPort",
                data: {port: portNumber},
                success: function(data){
                    if (data.error !== undefined){
                        showError(data.error);
                    }else{
                        showOK();
                    }
                }
            })
        }

        function showOK(){
            $("#ok").stop().finish().slideDown("fast").delay(3000).slideUp("fast");
        }

        function showError(msg){
            $("#error").find(".msg").text(msg);
            $("#error").stop().finish().slideDown("fast").delay(3000).slideUp("fast");
        }
       
    </script>
</body>
</html>